package com.example.docmanagement.controller;

import com.example.docmanagement.dto.request.RoleCreateRequest;
import com.example.docmanagement.dto.request.RoleQueryRequest;
import com.example.docmanagement.dto.request.RoleUpdateRequest;
import com.example.docmanagement.dto.request.RoleUserBatchRequest;
import com.example.docmanagement.dto.request.UpdateRolePermissionsRequest;
import com.example.docmanagement.dto.response.ApiResponse;
import com.example.docmanagement.dto.response.PageResponse;
import com.example.docmanagement.dto.response.RoleResponse;
import com.example.docmanagement.dto.response.UserResponse;
import com.example.docmanagement.service.RoleAdminService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 管理后台 - 角色管理接口
 */
@RestController
@RequestMapping("/api/v1/admin/roles")
@RequiredArgsConstructor
@Tag(name = "角色管理", description = "管理后台角色管理接口")
public class AdminRoleController {

    private final RoleAdminService roleAdminService;

    @GetMapping
    @Operation(summary = "角色分页查询", description = "分页查询角色列表")
    @PreAuthorize("hasAuthority('role:read') or hasRole('ADMIN')")
    public ApiResponse<PageResponse<RoleResponse>> listRoles(@ParameterObject @Valid RoleQueryRequest request) {
        return ApiResponse.success(roleAdminService.searchRoles(request));
    }

    @GetMapping("/{id}")
    @Operation(summary = "角色详情", description = "获取角色详细信息")
    @PreAuthorize("hasAuthority('role:view') or hasRole('ADMIN')")
    public ApiResponse<RoleResponse> getRole(
            @Parameter(description = "角色ID", required = true, example = "1") @PathVariable Long id) {
        return ApiResponse.success(roleAdminService.getRole(id));
    }

    @PostMapping
    @Operation(summary = "创建角色", description = "新增角色并可附带权限")
    @PreAuthorize("hasAuthority('role:create') or hasRole('ADMIN')")
    public ApiResponse<RoleResponse> createRole(@Valid @RequestBody RoleCreateRequest request) {
        return ApiResponse.success(roleAdminService.createRole(request), "角色创建成功");
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新角色", description = "更新角色基本信息及权限")
    @PreAuthorize("hasAuthority('role:update') or hasRole('ADMIN')")
    public ApiResponse<RoleResponse> updateRole(
            @Parameter(description = "角色ID", required = true, example = "1") @PathVariable Long id,
                                                @Valid @RequestBody RoleUpdateRequest request) {
        return ApiResponse.success(roleAdminService.updateRole(id, request), "角色更新成功");
    }

    @PutMapping("/{id}/permissions")
    @Operation(summary = "更新角色权限", description = "批量替换角色权限")
    @PreAuthorize("hasAuthority('role:assign-permission') or hasRole('ADMIN')")
    public ApiResponse<RoleResponse> updateRolePermissions(
            @Parameter(description = "角色ID", required = true, example = "1") @PathVariable Long id,
                                                           @Valid @RequestBody UpdateRolePermissionsRequest request) {
        return ApiResponse.success(roleAdminService.updateRolePermissions(id, request), "权限更新成功");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除角色", description = "删除角色（系统角色不可删除）")
    @PreAuthorize("hasAuthority('role:delete') or hasRole('ADMIN')")
    public ApiResponse<Void> deleteRole(
            @Parameter(description = "角色ID", required = true, example = "1") @PathVariable Long id) {
        roleAdminService.deleteRole(id);
        return ApiResponse.success(null, "角色删除成功");
    }

    @GetMapping("/{id}/users")
    @Operation(summary = "角色下的用户", description = "分页查询角色下的用户列表")
    @PreAuthorize("hasAuthority('role:view-users') or hasRole('ADMIN')")
    public ApiResponse<PageResponse<UserResponse>> listRoleUsers(
            @Parameter(description = "角色ID", required = true, example = "1") @PathVariable Long id,
            @Parameter(description = "页码（从1开始）", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页数量", example = "20") @RequestParam(defaultValue = "20") Integer pageSize) {
        return ApiResponse.success(roleAdminService.listRoleUsers(id, page, pageSize));
    }

    @PostMapping("/{id}/users")
    @Operation(summary = "为角色批量添加用户", description = "将多个用户分配到当前角色")
    @PreAuthorize("hasAuthority('role:assign-user') or hasRole('ADMIN')")
    public ApiResponse<Void> addRoleUsers(
            @Parameter(description = "角色ID", required = true, example = "1") @PathVariable Long id,
            @Valid @RequestBody RoleUserBatchRequest request) {
        roleAdminService.addUsersToRole(id, request.getUserIds());
        return ApiResponse.success(null, "已成功添加角色成员");
    }

    @DeleteMapping("/{id}/users")
    @Operation(summary = "批量移除角色下用户", description = "支持批量取消用户与角色的关联")
    @PreAuthorize("hasAuthority('role:assign-user') or hasRole('ADMIN')")
    public ApiResponse<Void> removeRoleUsers(
            @Parameter(description = "角色ID", required = true, example = "1") @PathVariable Long id,
            @Valid @RequestBody RoleUserBatchRequest request) {
        roleAdminService.removeUsersFromRole(id, request.getUserIds());
        return ApiResponse.success(null, "已成功移除角色成员");
    }
}


